﻿using isky.plugin;
using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace isky.Plugin
{
    public class UpdateSalesorderPlugin : IPlugin
    {
        //private readonly string _unsecureString;
        //private readonly string _secureString;
        private SalesorderapprovalHistoryDal salesorderapprovalHistoryDal = null;
        private CommonWcf commonWcf = null;
        /// <summary>
        /// 已审核
        /// </summary>
        private const int statusAudited= 100000004;
        /// <summary>
        /// 审核中
        /// </summary>
        private const int statusUnderReview = 100000006;

        /// <summary>
        /// 大于等于
        /// </summary>
        private const int greater = 100000000;
        /// <summary>
        /// 小于等于
        /// </summary>
        private const int less = 100000001;
        /// <summary>
        /// 节点一
        /// </summary>
        private const int constapprovalnode1 = 100000000;
        /// <summary>
        /// 节点二
        /// </summary>
        private const int constapprovalnode2 = 100000001;
        /// <summary>
        /// 节点三
        /// </summary>
        private const int constapprovalnode3 = 100000002;
        /// <summary>
        /// 节点四
        /// </summary>
        private const int constapprovalnode4 = 100000003;
        /// <summary>
        /// 节点五
        /// </summary>
        private const int constapprovalnode5 = 100000004;

        /// <summary>
        /// 审批历史节点
        /// </summary>
        private const int historyapprovalnode = 100000005;


        //public UpdateSalesorderPlugin() : base(typeof(UpdateSalesorderPlugin))
        //{
        //    salesorderapprovalHistorySql = new SalesorderapprovalHistorySql();
        //    commonWcf = new CommonWcf();
        //    //this._secureString = secureString;
        //    //this._unsecureString = unsecureString;
        //    base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(40, "Update", "salesorder", new Action<LocalPluginContext>(UpdatePostSalesorder)));
        //}

        public void Execute(IServiceProvider serviceProvider)
        {
            commonWcf = new CommonWcf();
            salesorderapprovalHistoryDal = new SalesorderapprovalHistoryDal();

            // Obtain the execution context service from the service provider.
            var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            // Obtain the Organization Service factory service from the service provider
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            var service = factory.CreateOrganizationService(context.UserId);
            try
            {
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    Entity preEntity = context.InputParameters["Target"] as Entity;
                    Entity PreImageEntity = (context.PreEntityImages != null && context.PreEntityImages.Contains("PreImage")) ? context.PreEntityImages["PreImage"] : null;
                    Guid entityId = context.PrimaryEntityId; if (entityId == Guid.Empty) return;
                    Guid userId = context.UserId; if (userId == Guid.Empty) return;
                    Guid historyEntityId = Guid.Empty;
                    #region 审核
                    if (preEntity != null && preEntity.Contains("new_processnotes"))
                    {
                        OptionSetValue optionstatus = commonWcf.GetAttributeInputOrImage<OptionSetValue>(preEntity, PreImageEntity, "new_status", null);
                        if (optionstatus == null)
                        {
                            throw new InvalidPluginExecutionException("该订单状态为空,请联系管理员！");
                        }
                        if (optionstatus != null && optionstatus.Value == statusUnderReview)
                        {
                            decimal zongjine = 0;

                            //订单总金额
                            if (commonWcf.GetAttributeInputOrImage<Money>(preEntity, PreImageEntity, "new_zongjine", null) != null)
                            {
                                zongjine = commonWcf.GetAttributeInputOrImage<Money>(preEntity, PreImageEntity, "new_zongjine", null).Value;
                            }
                            //预计到货日期
                            DateTime requestdeliveryby = commonWcf.GetAttributeInputOrImage<DateTime>(preEntity, PreImageEntity, "new_time", DateTime.MinValue).ToLocalTime();

                            //区域
                            EntityReference customeridReference = commonWcf.GetAttributeInputOrImage<EntityReference>(preEntity, PreImageEntity, "customerid", null);
                            if (customeridReference == null)
                            {
                                throw new InvalidPluginExecutionException("订单客户不能为空,请联系管理员！");
                            }
                            Entity accountentity = service.Retrieve("account", customeridReference.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet("new_quyu"));
                            if (accountentity == null)
                            {
                                throw new InvalidPluginExecutionException("该订单所在的客户区域不能为空,请联系管理员！");
                            }
                            OptionSetValue quyu = accountentity.GetAttributeDefaultValue<OptionSetValue>("new_quyu", null);
                            //OptionSetValue quyu = commonWcf.GetAttributeInputOrImage<OptionSetValue>(preEntity, PreImageEntity, "new_quyu", null);
                            if (quyu == null)
                            {
                                throw new InvalidPluginExecutionException("订单区域为空,请联系管理员！");
                            }
                            EntityCollection ProcessCollection = salesorderapprovalHistoryDal.GetSalesorderapprovalProcessInfo(service, quyu.Value);
                            if (ProcessCollection == null)
                            {
                                throw new InvalidPluginExecutionException("未找到符合条件的审批流程,请联系管理员！");
                            }
                            EntityCollection HistoryCollection = salesorderapprovalHistoryDal.GetSalesorderapprovalHistoryInfo(service, entityId);
                            //查询审批历史判断：1.为空时：默认从第五节点查询，是否符合规则，符合规则（节点编号>=第一节点） 否则 默认从第一节点查询审批
                            //                  2.不为空时：默认从第五节点查询，是否符合规则，符合规则（当前审批节点<=从第五节点查找规则(返回的节点)） 否则 默认熊当前节点查询审批
                            //审批历史记录为空则默认为第一流程节点
                            if (HistoryCollection == null
                                || HistoryCollection[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode", null).Value == historyapprovalnode)
                            {
                                int jiediannode;
                                if (HistoryCollection == null)
                                {
                                    jiediannode = constapprovalnode1;
                                }
                                else
                                {
                                    jiediannode = HistoryCollection[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode", null).Value;
                                }

                                //从第五节点查找规则
                                int approvalnode = ConditionalJudgment(ProcessCollection, zongjine, requestdeliveryby, 0);
                                if (approvalnode >= constapprovalnode1)
                                {
                                    //判断节点一的当前订单是否是区域经理
                                    //等于就按正常审批审批流程审批
                                    //不等于 判断订单创建人和审批流程审批人是否一致，
                                    Guid handler1Id = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler1", null).Id;
                                    if (handler1Id == userId)
                                    {
                                        bool role = VerificationRole(service, userId, entityId, ProcessCollection, constapprovalnode1, zongjine, requestdeliveryby);
                                        if (role == true)//当前用户等于管理员 
                                        {
                                            Guid nextthandlerid = GetNexthandlerId(constapprovalnode1, ProcessCollection);
                                            //创建审批历史记录
                                            historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, constapprovalnode1, nextthandlerid);
                                            if (historyEntityId != Guid.Empty)
                                            {
                                                //修改订单状态
                                                UpdateSalesOrderStatus1(service, entityId, historyEntityId, userId);
                                            }
                                        }
                                        else
                                        {
                                            //Guid thandlerid = GethandlerId(constapprovalnode2, ProcessCollection);
                                            //CreateHistorySalesorderapproval(service, userId, entityId, ProcessCollection, constapprovalnode1, zongjine, requestdeliveryby, out thandlerid, out historyEntityId);
                                            bool createbyresult = VerificationCreatedby(service, preEntity, PreImageEntity, userId, entityId, ProcessCollection, zongjine, requestdeliveryby, jiediannode);
                                            if (createbyresult == false)
                                            {

                                                bool roleresult = VerificationRole(service, userId, entityId, ProcessCollection, constapprovalnode1, zongjine, requestdeliveryby);
                                                if (roleresult == true)//当前用户等于管理员 
                                                {
                                                    Guid constapprovalnodeid = GetNexthandlerId(constapprovalnode1, ProcessCollection);
                                                    //创建审批历史记录
                                                    historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, constapprovalnode1, constapprovalnodeid);
                                                    if (historyEntityId != Guid.Empty)
                                                    {
                                                        //修改订单状态
                                                        UpdateSalesOrderStatus1(service, entityId, historyEntityId, userId);
                                                    }
                                                }
                                                else
                                                {
                                                    Guid constapprovalnodeid = GetNexthandlerId(constapprovalnode2, ProcessCollection);
                                                    CreateHistorySalesorderapproval(service, userId, entityId, ProcessCollection, constapprovalnode1, zongjine, requestdeliveryby, constapprovalnodeid, out historyEntityId);
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        //等于节点一时
                                        bool createbyresult = VerificationCreatedby(service, preEntity, PreImageEntity, userId, entityId, ProcessCollection, zongjine, requestdeliveryby, jiediannode);
                                        if (createbyresult == false)
                                        {

                                            bool role = VerificationRole(service, userId, entityId, ProcessCollection, constapprovalnode1, zongjine, requestdeliveryby);
                                            if (role == true)//当前用户等于管理员 
                                            {
                                                Guid constapprovalnodeid = GetNexthandlerId(constapprovalnode1, ProcessCollection);
                                                //创建审批历史记录
                                                historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, constapprovalnode1, constapprovalnodeid);
                                                if (historyEntityId != Guid.Empty)
                                                {
                                                    //修改订单状态
                                                    UpdateSalesOrderStatus1(service, entityId, historyEntityId, userId);
                                                }
                                            }
                                            else
                                            {
                                                Guid constapprovalnodeid = GetNexthandlerId(constapprovalnode2, ProcessCollection);
                                                CreateHistorySalesorderapproval(service, userId, entityId, ProcessCollection, constapprovalnode1, zongjine, requestdeliveryby, constapprovalnodeid, out historyEntityId);
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    //查找第一节点规则
                                    int approvalnode1 = ConditionalJudgment(ProcessCollection, zongjine, requestdeliveryby, constapprovalnode1);
                                    if (approvalnode1 == 0) { throw new InvalidPluginExecutionException("不符合审批流程规则,请联系管理员！"); }
                                    //等于节点一时
                                    if (approvalnode1 == constapprovalnode1)
                                    {
                                        bool createbyresult = VerificationCreatedby(service, preEntity, PreImageEntity, userId, entityId, ProcessCollection, zongjine, requestdeliveryby, jiediannode);
                                        if (createbyresult == false)
                                        {
                                            Guid constapprovalnodeid = GetNexthandlerId(constapprovalnode2, ProcessCollection);
                                            bool role = VerificationRole(service, userId, entityId, ProcessCollection, constapprovalnode1, zongjine, requestdeliveryby);
                                            if (role == true)//当前用户等于管理员 
                                            {
                                                //创建审批历史记录
                                                historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, constapprovalnode1, constapprovalnodeid);
                                                if (historyEntityId != Guid.Empty)
                                                {
                                                    //修改订单状态
                                                    UpdateSalesOrderStatus1(service, entityId, historyEntityId, userId);
                                                }
                                            }
                                            else
                                            {
                                                CreateHistorySalesorderapproval(service, userId, entityId, ProcessCollection, constapprovalnode1, zongjine, requestdeliveryby, constapprovalnodeid, out historyEntityId);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        //从第五节点查找规则
                                        int historyapprovalnode = ConditionalJudgment(ProcessCollection, zongjine, requestdeliveryby, 0);
                                        //当前审批节点+1等于 下一个节点
                                        int nextapprovalnode = HistoryCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode", null).Value + 1;
                                        if (nextapprovalnode <= historyapprovalnode)
                                        {
                                            bool role = VerificationRole(service, userId, entityId, ProcessCollection, nextapprovalnode, zongjine, requestdeliveryby);
                                            if (role == true)//当前用户等于管理员 
                                            {
                                                Guid nextthandlerid = GetNexthandlerId(nextapprovalnode, ProcessCollection);
                                                //创建审批历史记录
                                                historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, nextapprovalnode, nextthandlerid);
                                                if (historyEntityId != Guid.Empty)
                                                {
                                                    //修改订单状态
                                                    UpdateSalesOrderStatus1(service, entityId, historyEntityId, userId);
                                                }
                                            }
                                            else
                                            {
                                                Guid thandlerid = GethandlerId(nextapprovalnode, ProcessCollection);
                                                CreateHistorySalesorderapproval(service, userId, entityId, ProcessCollection, nextapprovalnode, zongjine, requestdeliveryby, thandlerid, out historyEntityId);
                                            }
                                        }
                                    }

                                }
                            }
                            else
                            {
                                //从第五节点查找规则
                                int approvalnode = ConditionalJudgment(ProcessCollection, zongjine, requestdeliveryby, 0);
                                //当前审批节点+1等于 下一个节点
                                int historyapprovalnode = HistoryCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode", null).Value + 1;
                                //等于节点一时
                                if (historyapprovalnode == constapprovalnode1)
                                {
                                    bool createbyresult = VerificationCreatedby(service, preEntity, PreImageEntity, userId, entityId, ProcessCollection, zongjine, requestdeliveryby, HistoryCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode", null).Value);
                                    if (createbyresult == false)
                                    {
                                        Guid constapprovalnodeid = GetNexthandlerId(constapprovalnode2, ProcessCollection);
                                        bool role = VerificationRole(service, userId, entityId, ProcessCollection, constapprovalnode1, zongjine, requestdeliveryby);
                                        if (role == true)//当前用户等于管理员 
                                        {
                                            //创建审批历史记录
                                            historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, constapprovalnode1, constapprovalnodeid);
                                            if (historyEntityId != Guid.Empty)
                                            {
                                                //修改订单状态
                                                UpdateSalesOrderStatus1(service, entityId, historyEntityId, userId);
                                            }
                                        }
                                        else
                                        {
                                            CreateHistorySalesorderapproval(service, userId, entityId, ProcessCollection, constapprovalnode1, zongjine, requestdeliveryby, constapprovalnodeid, out historyEntityId);
                                        }
                                    }
                                }
                                else
                                {
                                    //从第五节点查找规则
                                    int historyapprovalnodef = ConditionalJudgment(ProcessCollection, zongjine, requestdeliveryby, 0);
                                    //当前审批节点+1等于 下一个节点
                                    int nextapprovalnode = HistoryCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode", null).Value + 1;
                                    if (historyapprovalnodef >= nextapprovalnode)
                                    {
                                        bool role = VerificationRole(service, userId, entityId, ProcessCollection, nextapprovalnode, zongjine, requestdeliveryby);
                                        if (role == true)//当前用户等于管理员 
                                        {
                                            Guid nextthandlerid = GetNexthandlerId(nextapprovalnode, ProcessCollection);
                                            //创建审批历史记录
                                            historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, nextapprovalnode, nextthandlerid);
                                            if (historyEntityId != Guid.Empty)
                                            {
                                                //修改订单状态
                                                UpdateSalesOrderStatus1(service, entityId, historyEntityId, userId);
                                            }
                                        }
                                        else
                                        {
                                            Guid thandlerid = GethandlerId(nextapprovalnode, ProcessCollection);
                                            CreateHistorySalesorderapproval(service, userId, entityId, ProcessCollection, nextapprovalnode, zongjine, requestdeliveryby, thandlerid, out historyEntityId);
                                        }
                                    }
                                    else
                                    {
                                        bool role = VerificationRole1(service, userId, entityId);
                                        if (role == true)//当前用户等于管理员 
                                        {
                                            Guid nextthandlerid = GetNexthandlerId(nextapprovalnode, ProcessCollection);
                                            //创建审批历史记录
                                            historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, nextapprovalnode, nextthandlerid);
                                            if (historyEntityId != Guid.Empty)
                                            {
                                                //修改订单状态
                                                UpdateSalesOrderStatus1(service, entityId, historyEntityId, userId);
                                            }
                                        }
                                        else
                                        {
                                            Guid thandlerid = GethandlerId(nextapprovalnode, ProcessCollection);
                                            CreateHistorySalesorderapproval(service, userId, entityId, ProcessCollection, nextapprovalnode, zongjine, requestdeliveryby, thandlerid, out historyEntityId);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    #endregion

                    #region 驳回
                    if (preEntity != null && preEntity.Contains("new_overrulestatus"))
                    {
                        bool overrulestatusSetValue = preEntity.GetAttributeDefaultValue<bool>("new_overrulestatus", true);
                        OptionSetValue statusSetValue = PreImageEntity.GetAttributeDefaultValue<OptionSetValue>("new_status", null);
                        //区域
                        EntityReference customeridReference = commonWcf.GetAttributeInputOrImage<EntityReference>(preEntity, PreImageEntity, "customerid", null);
                        if (customeridReference == null)
                        {
                            throw new InvalidPluginExecutionException("订单客户不能为空,请联系管理员！");
                        }
                        Entity accountentity = service.Retrieve("account", customeridReference.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet("new_quyu"));
                        if (accountentity == null)
                        {
                            throw new InvalidPluginExecutionException("该订单所在的客户区域不能为空,请联系管理员！");
                        }
                        OptionSetValue quyu = accountentity.GetAttributeDefaultValue<OptionSetValue>("new_quyu", null);
                        EntityCollection ProcessCollection = salesorderapprovalHistoryDal.GetSalesorderapprovalProcessInfo(service, quyu.Value);
                        if (ProcessCollection == null)
                        {
                            throw new InvalidPluginExecutionException("未找到符合条件的审批流程,请联系管理员！");
                        }
                        //驳回状态改为是
                        if (overrulestatusSetValue == true && statusSetValue.Value == statusUnderReview)
                        {
                            //创建审批历史记录
                            CreateOverruleHistory(userId, service, entityId, ProcessCollection, preEntity);
                        }
                    }
                    #endregion
                    
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
                throw new NotImplementedException();
            }
        }


        /// <summary>
        /// 创建驳回审批历史记录
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="service"></param>
        /// <param name="entityId"></param>
        /// <param name="ProcessCollection"></param>
        private static void CreateOverruleHistory(Guid userId, IOrganizationService service, Guid entityId, EntityCollection ProcessCollection, Entity preEntity)
        {

            Entity entity = new Entity("new_salesorderapprovalhistory");
            //审批流程名称
            if (ProcessCollection.Entities[0].GetAttributeDefaultValue<string>("new_name", null) != null)
            {
                entity.Attributes["new_name"] = ProcessCollection.Entities[0].GetAttributeDefaultValue<string>("new_name");
            }
            //审批时间
            entity.Attributes["new_handletime"] = DateTime.Now.ToLocalTime();
            //审批状态-审批通过
            entity.Attributes["new_status"] = new OptionSetValue(100000001);
            //订单当前用户
            entity.Attributes["new_handler"] = new EntityReference("systemuser", userId);
            ///审批节点
            entity.Attributes["new_approvalnode"] = new OptionSetValue(100000005);
            //下级审批人
            if (ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler1") != null)
            {
                Guid nexthandlerId = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler1").Id;
                entity.Attributes["new_nexthandler"] = new EntityReference("systemuser", nexthandlerId);
            }
            //审批意见
            string overrulereason = preEntity.GetAttributeDefaultValue<string>("new_overrulereason", null);
            if (overrulereason == null)
            {
                throw new InvalidPluginExecutionException("审批意见为空,不能驳回！");
            }
            else
            {
                entity.Attributes["new_opinion"] = overrulereason;
            }
            //订单
            entity.Attributes["new_salesorder"] = new EntityReference("salesorder", entityId);

            if (ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_positionperson1", null) != null)
            {
                int historypositionperson1 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_positionperson1", null).Value;
                entity.Attributes["new_historypositionperson"] = new OptionSetValue(historypositionperson1);
            }
            service.Create(entity);
        }




        /// <summary>
        /// 判断订单创建人和审批流程第一节点的审核人是否一致
        /// 如果一致第一节点直接审核通过不生成审批记录，直接审批第二节点并生成审批记录
        /// </summary>
        /// <param name="service"></param>
        /// <param name="preEntity"></param>
        /// <param name="PreImageEntity"></param>
        /// <param name="entityCollection"></param>
        /// <param name="userId"></param>
        /// <param name="entityId"></param>
        /// <param name="ProcessCollection"></param>
        /// <param name="approvalnode"></param>
        public bool VerificationCreatedby(IOrganizationService service, Entity preEntity, Entity PreImageEntity, Guid userId, Guid entityId, EntityCollection ProcessCollection, decimal zongjine, DateTime requestdeliveryby, int jiedian)
        {
            Guid historyEntityId = Guid.Empty;
            EntityReference salesorderReference = commonWcf.GetAttributeInputOrImage<EntityReference>(preEntity, PreImageEntity, "createdby", null);
            Guid processhandlerId = GethandlerId(constapprovalnode1, ProcessCollection);

            Entity systemuserentity = service.Retrieve("systemuser", salesorderReference.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet("new_positionperson"));
            if (systemuserentity != null)
            {
                OptionSetValue positionpersonSetValue = systemuserentity.GetAttributeDefaultValue<OptionSetValue>("new_positionperson", null);
                //创建人==审批经理
                if (positionpersonSetValue != null && positionpersonSetValue.Value == 100000001)
                {
                    Guid constapprovalnodeid = Guid.Empty;
                    bool role = VerificationRole(service, userId, entityId, ProcessCollection, constapprovalnode2, zongjine, requestdeliveryby);
                    if (role == true)//当前用户等于管理员
                    {
                        //创建审批历史记录
                        historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, constapprovalnode2, constapprovalnodeid);
                        if (historyEntityId != Guid.Empty)
                        {
                            //修改订单状态
                            UpdateSalesOrderStatus1(service, entityId, historyEntityId, userId);
                        }
                    }
                    else
                    {
                        if (jiedian == constapprovalnode1 || jiedian == historyapprovalnode)
                        {
                            if (ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler3") != null)
                            {
                                //从第三节点查找规则
                                int historyapprovalnodef = ConditionalJudgment(ProcessCollection, zongjine, requestdeliveryby, constapprovalnode3);
                                if (historyapprovalnodef==0)
                                {
                                    constapprovalnodeid = Guid.Empty;
                                }
                                else
                                {
                                    constapprovalnodeid = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler3").Id;
                                }
                            }
                            else
                            {
                                constapprovalnodeid = Guid.Empty;
                            }

                            ////创建审批历史记录
                            //Guid historyEntityId1 = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, constapprovalnode2, constapprovalnodeid);
                            //第一级的下级审批人
                            Guid nextconstapprovalnodeid = GetNexthandlerId(constapprovalnode1, ProcessCollection);
                            if (userId != nextconstapprovalnodeid)
                            {
                                List<string> roleName = new List<string>();
                                EntityCollection roleCollection = salesorderapprovalHistoryDal.GetRoleName(service, userId);
                                if (roleCollection != null)
                                {
                                    roleCollection.Entities.ToList().ForEach(item =>
                                    {
                                        roleName.Add((string)item.GetAttributeDefaultValue<AliasedValue>("rol.name", null).Value);
                                    });
                                    role = roleName.Exists(t => t.Contains("ISKY-所有订单审核"));
                                    if (role == true)
                                    {
                                    }
                                    else
                                    {
                                        throw new InvalidPluginExecutionException("缺少审批权限，请联系管理员！");
                                    }
                                }
                                //throw new InvalidPluginExecutionException("缺少审批权限，请联系管理员！");
                            }
                        }
                        CreateHistorySalesorderapproval(service, userId, entityId, ProcessCollection, jiedian, zongjine, requestdeliveryby, constapprovalnodeid, out historyEntityId, 1);


                    }
                    return true;
                }
            }
            #region 作废
            //if (salesorderReference != null && processhandlerId != null)
            //{
            //    if (salesorderReference.Id == processhandlerId)
            //    {
            //        Guid constapprovalnodeid = Guid.Empty;
            //        bool role = VerificationRole(service, userId, entityId, ProcessCollection, constapprovalnode2, zongjine, requestdeliveryby);
            //        if (role == true)//当前用户等于管理员
            //        {
            //            //创建审批历史记录
            //            historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, constapprovalnode2, constapprovalnodeid);
            //            if (historyEntityId != Guid.Empty)
            //            {
            //                //修改订单状态
            //                UpdateSalesOrderStatus1(service, entityId, historyEntityId);
            //            }
            //        }
            //        else
            //        {
            //            if (userId == processhandlerId)
            //            {
            //                throw new InvalidPluginExecutionException("当前订单创建人和审批节点审批节点一致不允许审批！");
            //            }
            //            else
            //            {

            //                if (jiedian== constapprovalnode1 || jiedian == historyapprovalnode)
            //                {
            //                    if (ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler3") != null)
            //                    {
            //                        constapprovalnodeid = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler3").Id;
            //                    }
            //                    else
            //                    {
            //                        constapprovalnodeid = Guid.Empty;
            //                    }

            //                    ////创建审批历史记录
            //                    //Guid historyEntityId1 = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, constapprovalnode2, constapprovalnodeid);
            //                    //第一级的下级审批人
            //                    Guid nextconstapprovalnodeid = GetNexthandlerId(constapprovalnode1, ProcessCollection);
            //                    if (userId != nextconstapprovalnodeid)
            //                    {
            //                        throw new InvalidPluginExecutionException("缺少审批权限，请联系管理员！");
            //                    }
            //                }
            //                CreateHistorySalesorderapproval(service, userId, entityId, ProcessCollection, jiedian, zongjine, requestdeliveryby,  constapprovalnodeid, out historyEntityId,1);
            //            }
            //        }
            //        return true;
            //    }
            //}
            #endregion
            return false;
        }

        /// <summary>
        /// //修改订单状态为已审核
        /// </summary>
        /// <param name="service"></param>
        /// <param name="entityId"></param>
        /// <param name="ProcessCollection"></param>
        /// <param name="Indexapprovalnode"></param>
        private static void UpdateSalesOrderStatus(IOrganizationService service, Guid entityId, EntityCollection ProcessCollection, int Indexapprovalnode)
        {
            Entity salesorderentity = new Entity("salesorder", entityId);
            if (Indexapprovalnode == constapprovalnode1)
            {
                //节点审批人
                EntityReference handlerReference = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler2");
                if (handlerReference == null)
                {

                    salesorderentity.Attributes["new_status"] = new OptionSetValue(statusAudited);
                }
            }
            else if (Indexapprovalnode == constapprovalnode2)
            {
                //节点审批人
                EntityReference handlerReference = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler3");
                if (handlerReference == null)
                {
                    salesorderentity.Attributes["new_status"] = new OptionSetValue(statusAudited);
                }
            }
            else if (Indexapprovalnode == constapprovalnode3)
            {
                //节点审批人
                EntityReference handlerReference = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler4");
                if (handlerReference == null)
                {
                    salesorderentity.Attributes["new_status"] = new OptionSetValue(statusAudited);
                }
            }
            else if (Indexapprovalnode == constapprovalnode4)
            {
                //节点审批人
                EntityReference handlerReference = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler5");
                if (handlerReference == null)
                {
                    salesorderentity.Attributes["new_status"] = new OptionSetValue(statusAudited);
                }
            }
            else
            {
                salesorderentity.Attributes["new_status"] = new OptionSetValue(statusAudited);
            }
            service.Update(salesorderentity);
        }

        /// <summary>
        /// 修改订单状态，当前审批历史记录 下级审批人为空：订单状态修改（已审核）;不为空:订单状态修改(审核中)
        /// </summary>
        /// <param name="service"></param>
        /// <param name="entityId"></param>
        /// <param name="HistoryId">审批历史ID</param>
        private static void UpdateSalesOrderStatus1(IOrganizationService service, Guid entityId, Guid HistoryId,Guid userId)
        {
            Entity salesorderentity = new Entity("salesorder", entityId);
           Entity HistoryEntity = service.Retrieve("new_salesorderapprovalhistory", HistoryId, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));
            if (HistoryEntity!=null)
            {
                EntityReference nexthandler = HistoryEntity.GetAttributeDefaultValue<EntityReference>("new_nexthandler");
                if (nexthandler != null)
                {
                    salesorderentity.Attributes["new_status"] = new OptionSetValue(statusUnderReview);
                    salesorderentity.Attributes["new_reviewers"] = new EntityReference("systemuser", userId);
                   // salesorderentity.Attributes["new_reviewtime"] =DateTime.Now.ToLocalTime();

                }
                else
                {
                    salesorderentity.Attributes["new_status"] = new OptionSetValue(statusAudited);
                    salesorderentity.Attributes["new_reviewers"] = new EntityReference("systemuser", userId);
                   // salesorderentity.Attributes["new_reviewtime"] = DateTime.Now.ToLocalTime();
                }
                service.Update(salesorderentity);
            }
        }


        /// <summary>
        ///查找下级审批人
        /// </summary>
        /// <param name="approvalnode">当前节点</param>
        /// <param name="ProcessCollection"></param>
        /// <returns></returns>
        public Guid GetNexthandlerId(int approvalnode,EntityCollection ProcessCollection)
        {
            Guid handlerId = Guid.Empty;
            //下级审批人/审批节点
            if (approvalnode == constapprovalnode1)
            {
                if (ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler2") != null)
                {
                    handlerId = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler2").Id;
                }
            }
            else if (approvalnode == constapprovalnode2)
            {
                if (ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler3") != null)
                {
                    handlerId = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler3").Id;
                }
            }
            else if (approvalnode == constapprovalnode3)
            {
                if (ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler4") != null)
                {
                    handlerId = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler4").Id;
                }
            }
            else if (approvalnode == constapprovalnode4)
            {
                if (ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler5") != null)
                {
                    handlerId = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler5").Id;
                }
            }
            return handlerId;
        }

        /// <summary>
        /// 查询当前节点审批人
        /// </summary>
        /// <param name="approvalnode"></param>
        /// <param name="ProcessCollection"></param>
        public Guid GethandlerId(int approvalnode, EntityCollection ProcessCollection) {
            Guid handlerId = Guid.Empty;
            //节点一
            if (approvalnode == constapprovalnode1)
            {
                handlerId = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler1").Id;

            }
            else if (approvalnode == constapprovalnode2)
            {
                handlerId = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler2").Id;
            }
            else if (approvalnode == constapprovalnode3)
            {
                handlerId = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler3").Id;
            }
            else if (approvalnode == constapprovalnode4)
            {
                handlerId = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler4").Id;
            }
            else if (approvalnode == constapprovalnode5)
            {
                handlerId = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler5").Id;
            }
            else
            {
                throw new InvalidPluginExecutionException("没有5节点以外的审批人，请联系管理员！");
            }
            return handlerId;

        }


        /// <summary>
        /// 验证安全角色
        /// </summary>
        /// <param name="service"></param>
        /// <param name="userId"></param>
        /// <param name="entityId"></param>
        /// <param name="ProcessCollection"></param>
        /// <param name="jiedian">当前节点</param>
        /// <param name="zongjine"></param>
        /// <param name="requestdeliveryby"></param>
        /// <returns></returns>
        public bool VerificationRole(IOrganizationService service,Guid userId,Guid entityId, EntityCollection ProcessCollection,int jiedian,decimal zongjine,DateTime requestdeliveryby) {
            List<string> roleName = new List<string>();
            bool role = false;
            Guid constapprovalnodeid = Guid.Empty;
            Guid historyEntityId = Guid.Empty;
            EntityCollection roleCollection = salesorderapprovalHistoryDal.GetRoleName(service, userId);
            if (roleCollection != null)
            {
                roleCollection.Entities.ToList().ForEach(item =>
                {
                    roleName.Add((string)item.GetAttributeDefaultValue<AliasedValue>("rol.name", null).Value);
                });
                //|| t.Contains("ISKY-所有订单审核")
                role = roleName.Exists(t =>t.Contains("系统管理员") || t.Contains("系统定制员") );
                if (role == false)
                {
                    //节点一
                    if (jiedian == constapprovalnode1)
                    {
                        constapprovalnodeid = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler1").Id;
                    }
                    else if (jiedian == constapprovalnode2)
                    {
                        constapprovalnodeid = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler2").Id;
                    }
                    else if (jiedian == constapprovalnode3)
                    {
                        constapprovalnodeid = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler3").Id;
                    }
                    else if (jiedian == constapprovalnode4)
                    {
                        constapprovalnodeid = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler4").Id;
                    }
                    else if (jiedian == constapprovalnode5)
                    {
                        constapprovalnodeid = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler5").Id;
                    }
                    else
                    {
                        throw new InvalidPluginExecutionException("没有5节点以外的审批人，请联系管理员！");
                    }

                    Entity systemuserentity = service.Retrieve("systemuser", userId, new Microsoft.Xrm.Sdk.Query.ColumnSet("new_positionperson"));
                    if (systemuserentity != null)
                    {
                        OptionSetValue positionpersonSetValue = systemuserentity.GetAttributeDefaultValue<OptionSetValue>("new_positionperson", null);
                        //创建人==审批经理
                        if (positionpersonSetValue != null && positionpersonSetValue.Value == 100000001)
                        {
                            return false;
                        }
                        else
                        {
                            role = roleName.Exists(t => t.Contains("ISKY-所有订单审核"));
                            if (role == true)
                            {

                            }
                            else
                            {
                                //判断当前订单用户是否等于审批流程审核人
                                if (userId != constapprovalnodeid)
                                {
                                    throw new InvalidPluginExecutionException("缺少审批权限，请联系管理员！");
                                }
                                else
                                {
                                    return false;
                                }
                            }
                        }
                    }
                    return false;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                throw new InvalidPluginExecutionException("审批用户没有安全角色，请联系管理员！");
            }
        }



        public bool VerificationRole1(IOrganizationService service, Guid userId, Guid entityId)
        {
            List<string> roleName = new List<string>();
            bool role = false;
            Guid constapprovalnodeid = Guid.Empty;
            Guid historyEntityId = Guid.Empty;
            EntityCollection roleCollection = salesorderapprovalHistoryDal.GetRoleName(service, userId);
            if (roleCollection != null)
            {
                roleCollection.Entities.ToList().ForEach(item =>
                {
                    roleName.Add((string)item.GetAttributeDefaultValue<AliasedValue>("rol.name", null).Value);
                });
                //|| t.Contains("ISKY-所有订单审核")
                role = roleName.Exists(t => t.Contains("系统管理员") || t.Contains("系统定制员") );
                if (role == false)
                {
                        return false;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                throw new InvalidPluginExecutionException("审批用户没有安全角色，请联系管理员！");
            }
        }

        /// <summary>
        /// 创建审批历史记录
        /// </summary>
        /// <param name="service"></param>
        /// <param name="userId"></param>
        /// <param name="entityId"></param>
        /// <param name="ProcessCollection"></param>
        /// <param name="jiedian"></param>
        /// <param name="zongjine"></param>
        /// <param name="requestdeliveryby"></param>
        /// <param name="constapprovalnodeid"></param>
        /// <param name="historyEntityId"></param>
        private void CreateHistorySalesorderapproval(IOrganizationService service, Guid userId, Guid entityId, EntityCollection ProcessCollection, int jiedian, decimal zongjine, DateTime requestdeliveryby,  Guid constapprovalnodeid, out Guid historyEntityId,int status=0)
        {
           // constapprovalnodeid = Guid.Empty;
            //1、查找节下级节点的审批人
            //2、为节点一时; 判断节点二是否符合规则条件
            if (jiedian == constapprovalnode1 || jiedian== historyapprovalnode)
            {
                if (status==1)
                {
                    int approvalnode = ConditionalJudgment(ProcessCollection, zongjine, requestdeliveryby, 0);
                    if (approvalnode > jiedian)
                    {
                        //创建审批历史记录
                        historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, jiedian+1, constapprovalnodeid);
                    }
                    else
                    {
                        int Indexapprovalnode = ConditionalJudgment(ProcessCollection, zongjine, requestdeliveryby, constapprovalnode2);
                        if (Indexapprovalnode == 0)
                        {//不符合条件 创建审批记录，下级审批人没有值
                         //创建审批历史记录
                            historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, jiedian+1, Guid.Empty);
                        }
                        else//符合条件，创建审批记录，下级审批人有值
                        {
                            //创建审批历史记录
                            historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, jiedian+1, constapprovalnodeid);
                        }
                    }
                }
                else
                {
                        if (ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler2") != null)
                        {
                            constapprovalnodeid = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler2").Id;
                        }
                    int approvalnode = ConditionalJudgment(ProcessCollection, zongjine, requestdeliveryby, 0);
                    if (approvalnode > jiedian)
                    {
                        //创建审批历史记录
                        historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, jiedian, constapprovalnodeid);
                    }
                    else
                    {
                        int Indexapprovalnode = ConditionalJudgment(ProcessCollection, zongjine, requestdeliveryby, constapprovalnode2);
                        if (Indexapprovalnode == 0)
                        {//不符合条件 创建审批记录，下级审批人没有值
                         //创建审批历史记录
                            historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, jiedian, Guid.Empty);
                        }
                        else//符合条件，创建审批记录，下级审批人有值
                        {
                            //创建审批历史记录
                            historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, jiedian, constapprovalnodeid);
                        }
                    }
                }
              
            }
            else if (jiedian == constapprovalnode2)
            {
                if (ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler2") != null)
                {
                    constapprovalnodeid = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler3").Id;
                }
                else
                {
                    constapprovalnodeid = Guid.Empty;
                }

                int approvalnode = ConditionalJudgment(ProcessCollection, zongjine, requestdeliveryby, 0);
                if (approvalnode > jiedian)
                {
                    //创建审批历史记录
                    historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, jiedian, constapprovalnodeid);
                }
                else
                {
                    int Indexapprovalnode = ConditionalJudgment(ProcessCollection, zongjine, requestdeliveryby, constapprovalnode3);
                    if (Indexapprovalnode == 0)
                    {//不符合条件 创建审批记录，下级审批人没有值
                     //创建审批历史记录
                        historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, jiedian, Guid.Empty);
                    }
                    else//符合条件，创建审批记录，下级审批人有值
                    {
                        //创建审批历史记录
                        historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, jiedian, constapprovalnodeid);
                    }
                }
            }
            else if (jiedian == constapprovalnode3)
            {
                if (ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler4")!=null)
                {
                    constapprovalnodeid = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler4").Id;
                }
                else
                {
                    constapprovalnodeid =Guid.Empty;
                }

                int approvalnode = ConditionalJudgment(ProcessCollection, zongjine, requestdeliveryby, 0);
                if (approvalnode > jiedian)
                {
                    //创建审批历史记录
                    historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, jiedian, constapprovalnodeid);
                }
                else
                {
                    int Indexapprovalnode = ConditionalJudgment(ProcessCollection, zongjine, requestdeliveryby, constapprovalnode4);
                    if (Indexapprovalnode == 0)
                    {//不符合条件 创建审批记录，下级审批人没有值
                     //创建审批历史记录
                        historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, jiedian, Guid.Empty);
                    }
                    else//符合条件，创建审批记录，下级审批人有值
                    {
                        //创建审批历史记录
                        historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, jiedian, constapprovalnodeid);
                    }
                }
            }
            else if (jiedian == constapprovalnode4)
            {
                if (ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler2") != null)
                {
                    constapprovalnodeid = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler5").Id;
                }
                else
                {
                    constapprovalnodeid = Guid.Empty;
                }

                int approvalnode = ConditionalJudgment(ProcessCollection, zongjine, requestdeliveryby, 0);
                if (approvalnode > jiedian)
                {
                    //创建审批历史记录
                    historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, jiedian, constapprovalnodeid);
                }
                else
                {
                    int Indexapprovalnode = ConditionalJudgment(ProcessCollection, zongjine, requestdeliveryby, constapprovalnode5);
                    if (Indexapprovalnode == 0)
                    {//不符合条件 创建审批记录，下级审批人没有值
                     //创建审批历史记录
                        historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, jiedian, Guid.Empty);
                    }
                    else//符合条件，创建审批记录，下级审批人有值
                    {
                        //创建审批历史记录
                        historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, jiedian, constapprovalnodeid);
                    }
                }
            }
            else if (jiedian == constapprovalnode5)
            {
                constapprovalnodeid = Guid.Empty;
                //创建审批历史记录
                historyEntityId = CreateSalesorderapprovalHistory1(userId, service, entityId, ProcessCollection, jiedian, constapprovalnodeid);
            }
            else
            {
                throw new InvalidPluginExecutionException("没有5节点以外的审批人，请联系管理员！");
            }

            if (historyEntityId != Guid.Empty)
            {
                //修改订单状态
                UpdateSalesOrderStatus1(service, entityId, historyEntityId, userId);
            }
        }

        



        /// <summary>
        /// //生成历史审批记录，把订单状态改成审核中
        /// </summary>
        /// <param name="context"></param>
        /// <param name="service"></param>
        /// <param name="entityId"></param>
        /// <param name="ProcessCollection"></param>
        /// <param name="approvalnode"></param>
        private static void CreateSalesorderapprovalHistory(Guid userId, IOrganizationService service, Guid entityId, EntityCollection ProcessCollection, int approvalnode)
        {
            
            Entity entity = new Entity("new_salesorderapprovalhistory");
            //审批流程名称
            if (ProcessCollection.Entities[0].GetAttributeDefaultValue<string>("new_name", null) != null)
            {
                entity.Attributes["new_name"] = ProcessCollection.Entities[0].GetAttributeDefaultValue<string>("new_name");
            }
            //审批时间
            entity.Attributes["new_handletime"] = DateTime.Now.ToLocalTime();
            //审批状态-审批通过
            entity.Attributes["new_status"] = new OptionSetValue(100000000);
            //订单当前用户
            entity.Attributes["new_handler"] = new EntityReference("systemuser", userId);
            //下级审批人/审批节点
            if (approvalnode == constapprovalnode1)
            {
                if (ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode1", null) != null)
                {
                    entity.Attributes["new_approvalnode"] =new OptionSetValue(ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode1").Value);
                }
                if (ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler2") != null)
                {
                    Guid handler2Id = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler2").Id;
                    entity.Attributes["new_nexthandler"] = new EntityReference("systemuser", handler2Id);
                }

            }
            else if (approvalnode == constapprovalnode2)
            {

                if (ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode2", null) != null)
                {
                    entity.Attributes["new_approvalnode"] = new OptionSetValue(ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode2").Value);
                }
                if (ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler3") != null)
                {
                    Guid handler3Id = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler3").Id;
                    entity.Attributes["new_nexthandler"] = new EntityReference("systemuser", handler3Id);
                }
            }
            else if (approvalnode == constapprovalnode3)
            {

                if (ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode3", null) != null)
                {
                    entity.Attributes["new_approvalnode"] = new OptionSetValue(ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode3").Value);
                }
                if (ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler4") != null)
                {
                    Guid handler4Id = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler4").Id;
                    entity.Attributes["new_nexthandler"] = new EntityReference("systemuser", handler4Id);
                }
            }
            else if (approvalnode == constapprovalnode4)
            {

                if (ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode4", null) != null)
                {
                    entity.Attributes["new_approvalnode"] = new OptionSetValue(ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode4").Value);
                }
                if (ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler5") != null)
                {
                    Guid handler5Id = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler5").Id;
                    entity.Attributes["new_nexthandler"] = new EntityReference("systemuser", handler5Id);
                }
            }
            else if (approvalnode == constapprovalnode5)
            {

                if (ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode5", null) != null)
                {
                    entity.Attributes["new_approvalnode"] = new OptionSetValue(ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode5").Value);
                }
                entity.Attributes["new_nexthandler"] = null;
            }
            //订单
            entity.Attributes["new_salesorder"] = new EntityReference("salesorder", entityId);
            service.Create(entity);
        }

        /// <summary>
        /// 生成历史审批节点
        /// </summary>
        /// <param name="userId">当前订单用户ID</param>
        /// <param name="service"></param>
        /// <param name="entityId">当前订单实体ID</param>
        /// <param name="ProcessCollection"></param>
        /// <param name="approvalnode">当前节点</param>
        /// <param name="nexthandlerId">下级审批人</param>
        /// <returns></returns>
        private Guid CreateSalesorderapprovalHistory1(Guid userId, IOrganizationService service, Guid entityId, EntityCollection ProcessCollection, int approvalnode, Guid nexthandlerId)
        {

            Entity entity = new Entity("new_salesorderapprovalhistory");
            //审批流程名称
            if (ProcessCollection.Entities[0].GetAttributeDefaultValue<string>("new_name", null) != null)
            {
                entity.Attributes["new_name"] = ProcessCollection.Entities[0].GetAttributeDefaultValue<string>("new_name");
            }
            //审批时间
            entity.Attributes["new_handletime"] = DateTime.Now.ToLocalTime();
            //审批状态-审批通过
            entity.Attributes["new_status"] = new OptionSetValue(100000000);
            //订单当前用户
            entity.Attributes["new_handler"] = new EntityReference("systemuser", userId);
            //审批节点
            entity.Attributes["new_approvalnode"] = new OptionSetValue(approvalnode);

            //下级审批人  
            if (nexthandlerId == Guid.Empty)
            {
                entity.Attributes["new_nexthandler"] = null;
            }
            else
            {
                entity.Attributes["new_nexthandler"] = new EntityReference("systemuser", nexthandlerId);
            }
            //订单
            entity.Attributes["new_salesorder"] = new EntityReference("salesorder", entityId);


            //节点1审批人职位
            //区域
            Entity entitysalesorder = service.Retrieve("salesorder", entityId, new Microsoft.Xrm.Sdk.Query.ColumnSet("customerid"));
           
            if (entitysalesorder == null)
            {
                throw new InvalidPluginExecutionException("订单客户不能为空,请联系管理员！");
            }
          

          EntityReference customeridreference=  entitysalesorder.GetAttributeDefaultValue<EntityReference>("customerid", null);
            Entity accountentity = service.Retrieve("account", customeridreference.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet("new_quyu"));

          
            if (accountentity.GetAttributeDefaultValue<OptionSetValue>("new_quyu", null) == null)
            {
                throw new InvalidPluginExecutionException("该订单所在的客户区域不能为空,请联系管理员！");
            }
            
            if (accountentity.GetAttributeDefaultValue<OptionSetValue>("new_quyu", null) != null)
            {
                //if (entitysalesorder.GetAttributeDefaultValue<OptionSetValue>("new_quyu", null) != null)
                //{
                int quyu = accountentity.GetAttributeDefaultValue<OptionSetValue>("new_quyu", null).Value;
                EntityCollection Process = salesorderapprovalHistoryDal.GetSalesorderapprovalProcessInfo(service, quyu);
                if (approvalnode == constapprovalnode1  || approvalnode == historyapprovalnode)
                {
                    if (Process.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_positionperson1", null) != null)
                    {
                        int historypositionperson1 = Process.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_positionperson1", null).Value;
                        entity.Attributes["new_historypositionperson"] = new OptionSetValue(historypositionperson1);
                    }
                }
                else if (approvalnode == constapprovalnode2)
                {
                    if (Process.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_positionperson2", null) != null)
                    {
                        int historypositionperson2 = Process.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_positionperson2", null).Value;
                        entity.Attributes["new_historypositionperson"] = new OptionSetValue(historypositionperson2);
                    }
                }
                else if (approvalnode == constapprovalnode3)
                {
                    if (Process.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_positionperson3", null) != null)
                    {
                        int historypositionperson3 = Process.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_positionperson3", null).Value;
                        entity.Attributes["new_historypositionperson"] = new OptionSetValue(historypositionperson3);
                    }
                }
                else if (approvalnode == constapprovalnode4)
                {
                    if (Process.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_positionperson4", null) != null)
                    {
                        int historypositionperson4 = Process.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_positionperson4", null).Value;
                        entity.Attributes["new_historypositionperson"] = new OptionSetValue(historypositionperson4);
                    }
                }
                else if (approvalnode == constapprovalnode5)
                {
                    if (Process.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_positionperson5", null) != null)
                    {
                        int historypositionperson5 = Process.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_positionperson5", null).Value;
                        entity.Attributes["new_historypositionperson"] = new OptionSetValue(historypositionperson5);
                    }
                }
            }
            return service.Create(entity);
        }


        /// <summary>
        /// 从节点5往下遍历所有节点的条件，只要符合一个条件即可；（例如最高符合节点5的条件，则不考虑前面节点1-4的条件，每一个节点的审批人都可以按顺序审批）
        /// </summary>
        /// <param name="ProcessCollection">流程集合</param>
        /// <param name="zongjine">订单总金额</param>
        /// <param name="requestdeliveryby">订单预计到货日期</param>
        /// <param name="historyapprovalnode">历史审批记录节点</param>
        /// <returns></returns>
        public int ConditionalJudgment(EntityCollection ProcessCollection,decimal zongjine,DateTime requestdeliveryby,int historyapprovalnode) {
            //默认第一节点
            if (historyapprovalnode!=0)
            {
                //第五节点
                if (historyapprovalnode == constapprovalnode5)
                {
                    //节点五审批人
                    EntityReference handler5Reference = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler5");
                    if (handler5Reference != null)
                    {
                        int approvalnode5 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode5").Value;
                        if (approvalnode5 == constapprovalnode5)
                        {
                            int deliverytime5 = ProcessCollection.Entities[0].GetAttributeDefaultValue<int>("new_deliverytime5",0);
                            OptionSetValue deliverytimesign5 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_deliverytimesign5");
                            decimal orderamount5 = ProcessCollection.Entities[0].GetAttributeDefaultValue<decimal>("new_orderamount5");
                            OptionSetValue orderamountsign5 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_orderamountsign5");
                            if (deliverytimesign5 != null && orderamountsign5 != null)
                            {
                                bool result = JudgmentNode(deliverytimesign5, deliverytime5, orderamountsign5, orderamount5, requestdeliveryby, zongjine);
                                if (result == true)
                                {
                                    return approvalnode5;
                                }
                            }
                        }
                    }
                }
                else if (historyapprovalnode == constapprovalnode4)//第四节点
                {
                    //节点四审批人
                    EntityReference handler4Reference = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler4");
                    if (handler4Reference != null)
                    {
                        int approvalnode4 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode4").Value;
                        if (approvalnode4 == constapprovalnode4)
                        {
                            int deliverytime4 = ProcessCollection.Entities[0].GetAttributeDefaultValue<int>("new_deliverytime4",0);
                            OptionSetValue deliverytimesign4 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_deliverytimesign4");
                            decimal orderamount4 = ProcessCollection.Entities[0].GetAttributeDefaultValue<decimal>("new_orderamount4");
                            OptionSetValue orderamountsign4 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_orderamountsign4");
                            if (deliverytimesign4 != null && orderamountsign4 != null)
                            {
                                bool result = JudgmentNode(deliverytimesign4, deliverytime4, orderamountsign4, orderamount4, requestdeliveryby, zongjine);
                                if (result == true)
                                {
                                    return approvalnode4;
                                }
                            }
                        }
                    }
                }
                else if (historyapprovalnode == constapprovalnode3)
                {//第三节点

                    //节点三审批人
                    EntityReference handler3Reference = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler3");
                    if (handler3Reference != null)
                    {
                        int approvalnode3 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode3").Value;
                        if (approvalnode3 == constapprovalnode3)
                        {
                            int deliverytime3 = ProcessCollection.Entities[0].GetAttributeDefaultValue<int>("new_deliverytime3",0);
                            OptionSetValue deliverytimesign3 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_deliverytimesign3");
                            decimal orderamount3 = ProcessCollection.Entities[0].GetAttributeDefaultValue<decimal>("new_orderamount3");
                            OptionSetValue orderamountsign3 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_orderamountsign3");
                            if (deliverytimesign3 != null && orderamountsign3 != null)
                            {
                                bool result = JudgmentNode(deliverytimesign3, deliverytime3, orderamountsign3, orderamount3, requestdeliveryby, zongjine);
                                if (result == true)
                                {
                                    return approvalnode3;
                                }
                            }
                        }
                    }

                }
                else if (historyapprovalnode == constapprovalnode2)
                {//第二节点
                    //节点二审批人
                    EntityReference handler2Reference = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler2");
                    if (handler2Reference != null)
                    {
                        int approvalnode2 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode2").Value;
                        if (approvalnode2 == constapprovalnode2)
                        {
                            int deliverytime2 = ProcessCollection.Entities[0].GetAttributeDefaultValue<int>("new_deliverytime2",0);
                            OptionSetValue deliverytimesign2 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_deliverytimesign2");
                            decimal orderamount2 = ProcessCollection.Entities[0].GetAttributeDefaultValue<decimal>("new_orderamount2");
                            OptionSetValue orderamountsign2 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_orderamountsign2");
                            if (deliverytimesign2 != null && orderamountsign2 != null)
                            {
                                bool result = JudgmentNode(deliverytimesign2, deliverytime2, orderamountsign2, orderamount2, requestdeliveryby, zongjine);
                                if (result == true)
                                {
                                    return approvalnode2;
                                }
                            }
                        }
                    }
                }
                else {

                    //节点一审批人
                    EntityReference handler1Reference = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler1");
                    if (handler1Reference != null)
                    {
                        int approvalnode1 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode1").Value;
                        if (approvalnode1 == constapprovalnode1)
                        {
                            int deliverytime1 = ProcessCollection.Entities[0].GetAttributeDefaultValue<int>("new_deliverytime1",0);
                            OptionSetValue deliverytimesign1 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_deliverytimesign1");
                            decimal orderamount1 = ProcessCollection.Entities[0].GetAttributeDefaultValue<decimal>("new_orderamount1");
                            OptionSetValue orderamountsign1 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_orderamountsign1");
                            if (deliverytimesign1 != null && orderamountsign1 != null)
                            {
                                bool result = JudgmentNode(deliverytimesign1, deliverytime1, orderamountsign1, orderamount1, requestdeliveryby, zongjine);
                                if (result == true)
                                {
                                    return approvalnode1;
                                }
                            }
                        }
                    }
                }            
            }
            else
            {

                //节点五审批人
                EntityReference handler5Reference = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler5");
                if (handler5Reference != null)
                {
                    int approvalnode5 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode5").Value;
                    if (approvalnode5 == 100000004)
                    {
                        int deliverytime5 = ProcessCollection.Entities[0].GetAttributeDefaultValue<int>("new_deliverytime5", 0);
                        OptionSetValue deliverytimesign5 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_deliverytimesign5");
                        decimal orderamount5 = ProcessCollection.Entities[0].GetAttributeDefaultValue<decimal>("new_orderamount5");
                        OptionSetValue orderamountsign5 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_orderamountsign5");
                        if (deliverytimesign5 != null && orderamountsign5 != null)
                        {
                            bool result = JudgmentNode(deliverytimesign5, deliverytime5, orderamountsign5, orderamount5, requestdeliveryby, zongjine);
                            if (result == true)
                            {
                                return approvalnode5;
                            }
                        }
                    }
                }
                //节点四审批人
                EntityReference handler4Reference = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler4");
                if (handler4Reference != null)
                {
                    int approvalnode4 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode4").Value;
                    if (approvalnode4 == 100000003)
                    {
                        int deliverytime4 = ProcessCollection.Entities[0].GetAttributeDefaultValue<int>("new_deliverytime4",0);
                        OptionSetValue deliverytimesign4 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_deliverytimesign4");
                        decimal orderamount4 = ProcessCollection.Entities[0].GetAttributeDefaultValue<decimal>("new_orderamount4");
                        OptionSetValue orderamountsign4 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_orderamountsign4");
                        if (deliverytimesign4 != null && orderamountsign4 != null)
                        {
                            bool result = JudgmentNode(deliverytimesign4, deliverytime4, orderamountsign4, orderamount4, requestdeliveryby, zongjine);
                            if (result == true)
                            {
                                return approvalnode4;
                            }
                        }
                    }
                }
                //节点三审批人
                EntityReference handler3Reference = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler3");
                if (handler3Reference != null)
                {
                    int approvalnode3 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode3").Value;
                    if (approvalnode3 == 100000002)
                    {
                        int deliverytime3 = ProcessCollection.Entities[0].GetAttributeDefaultValue<int>("new_deliverytime3", 0);
                        OptionSetValue deliverytimesign3 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_deliverytimesign3");
                        decimal orderamount3 = ProcessCollection.Entities[0].GetAttributeDefaultValue<decimal>("new_orderamount3");
                        OptionSetValue orderamountsign3 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_orderamountsign3");
                        if (deliverytimesign3 != null && orderamountsign3 != null)
                        {
                            bool result = JudgmentNode(deliverytimesign3, deliverytime3, orderamountsign3, orderamount3, requestdeliveryby, zongjine);
                            if (result == true)
                            {
                                return approvalnode3;
                            }
                        }
                    }
                }
                //节点二审批人
                EntityReference handler2Reference = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler2");
                if (handler2Reference != null)
                {
                    int approvalnode2 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode2").Value;
                    if (approvalnode2 == 100000001)
                    {
                        int deliverytime2 = ProcessCollection.Entities[0].GetAttributeDefaultValue<int>("new_deliverytime2",0);
                        OptionSetValue deliverytimesign2 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_deliverytimesign2");
                        decimal orderamount2 = ProcessCollection.Entities[0].GetAttributeDefaultValue<decimal>("new_orderamount2");
                        OptionSetValue orderamountsign2 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_orderamountsign2");
                        if (deliverytimesign2 != null && orderamountsign2 != null)
                        {
                            bool result = JudgmentNode(deliverytimesign2, deliverytime2, orderamountsign2, orderamount2, requestdeliveryby, zongjine);
                            if (result == true)
                            {
                                return approvalnode2;
                            }
                        }
                    }
                }
                //节点一审批人
                EntityReference handler1Reference = ProcessCollection.Entities[0].GetAttributeDefaultValue<EntityReference>("new_handler1");
                if (handler1Reference != null)
                {
                    int approvalnode1 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_approvalnode1").Value;
                    if (approvalnode1 == 100000000)
                    {
                        int deliverytime1 = ProcessCollection.Entities[0].GetAttributeDefaultValue<int>("new_deliverytime1",0);
                        OptionSetValue deliverytimesign1 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_deliverytimesign1");
                        decimal orderamount1 = ProcessCollection.Entities[0].GetAttributeDefaultValue<decimal>("new_orderamount1");
                        OptionSetValue orderamountsign1 = ProcessCollection.Entities[0].GetAttributeDefaultValue<OptionSetValue>("new_orderamountsign1");
                        if (deliverytimesign1 != null && orderamountsign1 != null)
                        {
                            bool result = JudgmentNode(deliverytimesign1, deliverytime1, orderamountsign1, orderamount1, requestdeliveryby, zongjine);
                            if (result == true)
                            {
                                return approvalnode1;
                            }
                        }
                    }
                }
            }
            return 0; 
        }

        /// <summary>
        /// 判断是否满足条件
        /// </summary>
        /// <param name="deliverytimesign"></param>
        /// <param name="deliverytime"></param>
        /// <param name="orderamountsign"></param>
        /// <param name="orderamount"></param>
        /// <param name="requestdeliveryby"></param>
        /// <param name="zongjine"></param>
        /// <returns></returns>
        public bool JudgmentNode(OptionSetValue deliverytimesign, int deliverytime, OptionSetValue orderamountsign, decimal orderamount, DateTime requestdeliveryby, decimal zongjine)
        {
            int interval = new TimeSpan(requestdeliveryby.ToLocalTime().Ticks - DateTime.Now.ToLocalTime().Ticks).Days;
            TimeSpan sp = DateTime.Now.ToLocalTime().Subtract(requestdeliveryby.ToLocalTime());
            int interval1 = sp.Days;
            if (deliverytimesign.Value == greater)
            {
                if (interval >= deliverytime)
                {
                    return true;
                }
            }
            else if (deliverytimesign.Value == less)
            {
                if (interval <= deliverytime)
                {
                    return true;
                }
            }

            if (orderamountsign.Value == greater)
            {
                if (zongjine >= orderamount)
                {
                    return true;
                }
            }
            else if (orderamountsign.Value == less)
            {
                if (zongjine <= orderamount)
                {
                    return true;
                }
            }
            return false;
        }


        
       

    }
}
